var express = require("express");
var app = express();
var morgan = require("morgan");
var fs = require("fs");
var path = require("path");
var _ = require("loadsh");
var dayjs = require("dayjs");
var cookie_parser = require("cookie-parser");
var customParseFormat = require("dayjs/plugin/customParseFormat");
dayjs.extend(customParseFormat);
var multiparty = require("multiparty");
app.use("/js", express.static("./public/js"));
var FileStreamRotator = require("file-stream-rotator");
var logDirectory = path.join(__dirname, "log");
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);
var accessLogStream = FileStreamRotator.getStream({
  date_format: "YYYYMMDD",
  filename: path.join(logDirectory, "access-%DATE%.log"),
  frequency: "daily",
  verbose: false,
});
morgan.token("from", function (req, res) {
  return req.query.from || "-";
});
// 日志格式 short joke
morgan.format("joke", "[joke] :method :url :status :from");
app.use(morgan("combined", { stream: accessLogStream }));
const body = require("body-parser");
const Token = require("../config/token");
app.use("/public", express.static("public"));
app.use(body.json()); //body-parser 解析json格式数据
app.use(cookie_parser());
app.use(
  body.urlencoded({
    //此项必须在 bodyParser.json 下面,为参数编码
    extended: true,
  })
);
const expressSwagger = require("express-swagger-generator")(app);
const options = {
  swaggerDefinition: {
    info: {
      description: "吴迪测试",
      title: "Swagger - 吴迪分享",
      version: "1.0.0",
    },
    host: "localhost:3000",
    basePath: "/",
    produces: ["application/json", "application/xml"],
    schemes: ["http", "https"],
    securityDefinitions: {
      JWT: {
        type: "apiKey",
        in: "header",
        name: "token",
        description: "",
      },
    },
  },
  route: {
    url: "/swagger",
    docs: "/swagger.json", //swagger文件 api
  },
  basedir: __dirname, //app absolute path
  files: ["../router/**/*.js"], //Path to the API handle folder
};
expressSwagger(options);
app.use("*", function (req, res, next) {
  res.setHeader("Access-Control-Allow-Credentials", "true");
  res.header("Access-Control-Allow-Origin", "http://127.0.0.1:5500");
  res.header("Access-Control-Allow-Origin", "http://localhost:8000");
  res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
  res.header("Access-Control-Allow-Headers", "*");
  res.header("setcookie", "123");
  res.header("Access-Control-Expose-Headers", "setcookie,X-Powered-By");
  if (req.headers.token) {
    let user_token = Token.decrypt(req.headers.token);
    if (user_token.token) {
      req.headers.userInfo = user_token.userInfo;
      // res.json({
      //   user_token,
      // });
      next();
    } else {
      res.json({
        user_token,
      });
    }
  } else if (["/login/user"].includes(req.baseUrl)) {
    next();
  } else {
    res.json({
      code: -1,
      message: "token无效",
      data: [],
    });
  }
});

// app.get("/img", function (req, res) {
//   var filepath = "./3.jpg";
//   var bData = fs.readFileSync(filepath);
//   var base64Str = bData.toString("base64");
//   var datauri = "data:image/png;base64," + base64Str;
//   res.json({ url: datauri });
// });
// app.post("/upla", (req, res) => {
//   // 接收文件上传
//   let form = new multiparty.Form({
//     uploadDir: "./public", //指定上传的文件路径
//   });
//   form.parse(req, (err, field, files) => {
//     let arr =
//       files &&
//       files.file.map((x) => {
//         // 必须这样写
//         fs.rename(x.path, "./public/" + x.originalFilename, () => {
//           console.log("改名");
//         });
//       });
//     res.end(
//       JSON.stringify({
//         ok: 200,
//       })
//     );
//   });
//   form.on("field", (name, value) => {
//     // name:字段名
//     // value:值
//     console.log("数据:", name, value);
//   });
//   //接收文件数据
//   form.on("file", (name, file) => {
//     console.log("文件:", name, file);
//   });
//   //表单解析完成
//   form.on("close", () => {
//     console.log("完成");
//   });
// });
// app.post("/send", async (req, res) => {
//   function read() {
//     return new Promise((resolve, rejects) => {
//       fs.readFile("./public/3.jpg", function (err, data) {
//         resolve(data);
//         rejects(err);
//       });
//     });
//   }
//   let data = await read();
//   try {
//     res.send(data);
//   } catch (error) {
//     res.send(500);
//   }
// });
// app.get("/video", async (req, res) => {
//   function read() {
//     return new Promise((resolve, rejects) => {
//       fs.readFile("./movie.mp4", function (err, data) {
//         resolve(data);
//         rejects(err);
//       });
//     });
//   }
//   let data = await read();
//   try {
//     res.send(data);
//   } catch (error) {
//     res.send(500);
//   }
// });
// app.post("/cookie", (req, res) => {
//   res.json({
//     cookie: req.cookies,
//   });
// });

module.exports = { app, express };
